package modules

import (
	"github.com/disintegration/imaging"
	"github.com/fogleman/gg"
	"image"
	"image/color"
	"math"
	"strings"
	"time"
	"virchow_poster/utils"
)

type Images struct {
	PositionX   int    `json:"positionX"`
	PositionY   int    `json:"positionY"`
	ImageWidth  int    `json:"imageWidth"`
	ImageHeight int    `json:"imageHeight"`
	ImageUrl    string `json:"imageUrl"`
	CircleClip  bool   `json:"circleClip"`
}

// 插入图片
func drawImages(poster *Poster, canvas *gg.Context) {
	for _, _image := range poster.Images {
		var localFilePath string
		if strings.HasPrefix(strings.ToLower(strings.TrimSpace(_image.ImageUrl)), "http") {
			localFilePath = utils.SaveHttpImage(_image.ImageUrl, poster.SavePath+"/downloads", time.Now().Format("20060102150405.000000"))
		} else {
			localFilePath = _image.ImageUrl
		}
		figure, _ := imaging.Open(localFilePath)
		src := imaging.Resize(figure, _image.ImageWidth, _image.ImageHeight, imaging.Lanczos)
		if _image.CircleClip {
			r := int(math.Min(float64(_image.ImageWidth), float64(_image.ImageHeight)))
			src = circleMask(r, src)
		}
		canvas.DrawImageAnchored(src, _image.PositionX, _image.PositionY, 0, 0)
	}
}

// 裁剪成圆形
func circleMask(d int, image *image.NRGBA) *image.NRGBA {
	for x := 0; x < d; x++ {
		for y := 0; y < d; y++ {
			dis := math.Sqrt(math.Pow(float64(x-d/2), 2) + math.Pow(float64(y-d/2), 2))
			if dis > float64(d)/2 {
				image.Set(x, y, color.RGBA{0, 0, 0, 0})
			} else {
				image.Set(x, y, image.At(x, y))
			}
		}
	}
	return image
}
